﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ICT4Events.Models;
using System.Net.Mail;

namespace ICT4Events.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(FormCollection form)
        {
            try
            {
                List<Persoon> logins = DatabaseKoppeling.GetInlogGegevens(Convert.ToInt32(form["reserveringsnummer"]));
                foreach (Persoon p in logins)
                {
                    if (form["rfid"] == p.Rfid && form["wachtwoord"] == p.Wachtwoord)
                    {
                        HttpCookie cookieType = new HttpCookie("type", p.Type);
                        cookieType.Expires = DateTime.Now.AddDays(1);
                        HttpCookie cookieRfid = new HttpCookie("rfid", p.Rfid);
                        cookieRfid.Expires = DateTime.Now.AddDays(1);
                        HttpCookie cookieRes = new HttpCookie("res", form["reserveringsnummer"]);
                        cookieRes.Expires = DateTime.Now.AddDays(1);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookieRes);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookieRfid);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookieType);

                        return RedirectToAction("Reservering", "Home");
                    }
                }
                ModelState.AddModelError("", "Ingevoerde gegevens zijn onjuist!");
            }
            catch 
            {
                ModelState.AddModelError("", "Ingevoerde gegevens zijn onjuist!");
                return View();
            }
            return View();
            
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("rfid"))
            {
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["rfid"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("type"))
            {
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["type"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("res"))
            {
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["res"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult Aanvraag()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Aanvraag(FormCollection form)
        {
            ModelState.Clear();
            if (String.IsNullOrEmpty( form["naam"]))
                ModelState.AddModelError("Naam", "U hoort een naam in te vullen.");
            if (String.IsNullOrEmpty(form["straat"]))
                ModelState.AddModelError("Straat", "U hoort een straat in te vullen.");
            if (String.IsNullOrEmpty(form["woonplaats"]))
                ModelState.AddModelError("Woonplaats", "U hoort een woonplaats in te vullen.");
            if (String.IsNullOrEmpty(form["postcode"]))
                ModelState.AddModelError("Postcode", "U hoort een postcode in te vullen.");
            if (String.IsNullOrEmpty(form["rijbewijsnummer"]))
                ModelState.AddModelError("Sofi", "U hoort een rijbewijsnummer in te vullen.");
            if (String.IsNullOrEmpty(form["rekeningnummer"]))
                ModelState.AddModelError("rekeningnummer", "U hoort een rekeningnummer in te vullen.");

            if (ModelState.IsValid)
            {
                var res = DatabaseKoppeling.GetNieuwReserveringsnummer();
                DatabaseKoppeling.AddReservering(new Reservering(res, "false"));

                BetalendeKlant bk = new BetalendeKlant(DatabaseKoppeling.GetVrijRFID(), form["naam"], form["rijbewijsnummer"], form["email"], form["telefoon"], form["woonplaats"], form["straat"], form["rekeningnummer"], form["postcode"], res);

                DatabaseKoppeling.AddBetalendeKlant(bk);
                try
                {
                    Email.SendEmail(new MailAddress(bk.Email),
                              "ICT4Events account aangemaakt",
                              "Beste " + bk.Naam +
                              ",\n\nEr is een account voor u aangemaakt. Vanaf nu kunt u inloggen met de volgende gegevens:\nReserveringsnummer: " + bk.Reserveringsnummer.ToString() + "\nRFID: " +
                              bk.Rfid + "\nWachtwoord: " + bk.Wachtwoord + "\n\nMet vriendelijke groeten,\nICT4Events staff");
                    return RedirectToAction("AanvraagSucces", "Account");
                }
                catch (Exception ex)
                {
                    RedirectToAction("Error", "Shared", ex.Message);
                }
            }
            return View();
        }

        public ActionResult AanvraagSucces()
        {
            return View();
        }

    }
}
